package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 *
 * @author cxb
 * @date 2025-10-13
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     *
     * @param deviceDto 设备
     * @return 结果
     */
    @Override
    public int updateDevice(DeviceDto deviceDto) {
        Long count = lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).ne(Device::getId, deviceDto.getId()).count();
        if (count > 0) {
            throw new BaseException("设备名称已存在");
        }
        if (deviceDto.getLocationType().equals(0)) {
            deviceDto.setPhysicalLocationType(-1);
        }
        count = lambdaQuery().eq(Device::getLocationType, deviceDto.getLocationType()).eq(Device::getBindingLocation, deviceDto.getBindingLocation()).eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType()).eq(Device::getProductKey, deviceDto.getProductKey()).ne(Device::getId, deviceDto.getId()).count();
        if (count > 0) {
            throw new BaseException("同一位置绑定了相同的产品");
        }

        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceDto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(deviceDto.getDeviceName());
        request.withBody(body);
        UpdateDeviceResponse response = client.updateDevice(request);
        if (response.getHttpStatusCode() != 200) {
            log.error("物联网接口 - 修改设备失败{}", response);
            throw new BaseException("物联网接口 - 修改设备失败");
        }
        Device device = new Device();
        BeanUtils.copyProperties(deviceDto, device);
        device.setBindingLocation(String.valueOf(deviceDto.getBindingLocation()));
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void syncProductList() {
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        listProductsRequest.setLimit(50);
        ListProductsResponse response = null;
        try {
            response = client.listProducts(listProductsRequest);
        } catch (Exception e) {
            log.error("物联网接口 - 获取产品列表失败", e);
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        if (response.getHttpStatusCode() != 200) {
            log.error("物联网接口 - 获取产品列表失败{}", response);
            throw new BaseException("物联网接口 - 获取产品列表失败");
        }
        List<ProductSummary> products = response.getProducts();
        if (CollectionUtil.isEmpty(products)) {
            log.error("物联网接口 - 获取产品列表为空");
            throw new BaseException("物联网接口 - 获取产品列表为空");
        }
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {
        String allProduct = redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        if (StrUtil.isEmpty(allProduct)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(allProduct, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void register(DeviceDto deviceDto) {
        Long count = lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).count();
        if (count > 0) {
            throw new BaseException("设备名称已存在");
        }
        count = lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()).count();
        if (count > 0) {
            throw new BaseException("设备标识码已存在");
        }
        if (deviceDto.getLocationType().equals(0)) {
            deviceDto.setPhysicalLocationType(-1);
        }
        count = lambdaQuery().eq(Device::getLocationType, deviceDto.getLocationType()).eq(Device::getBindingLocation, deviceDto.getBindingLocation()).eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType()).eq(Device::getProductKey, deviceDto.getProductKey()).count();
        if (count > 0) {
            throw new BaseException("同一位置绑定了相同的产品");
        }
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        String secret = UUID.randomUUID().toString().replace("-", "");
        body = body.withNodeId(deviceDto.getNodeId()).withDeviceName(deviceDto.getDeviceName()).withProductId(deviceDto.getProductKey()).withAuthInfo(new AuthInfo().withSecret(secret));
        request.withBody(body);
        AddDeviceResponse response = null;
        try {
            response = client.addDevice(request);
        } catch (BaseException e) {
            log.error("物联网接口 - 注册设备失败{}", e);
            throw new BaseException("物联网接口 - 注册设备失败");
        }
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        save(device);
    }

    @Override
    public DeviceDetailVo detail(String iotId) {
        Device device = lambdaQuery().eq(Device::getIotId, iotId).one();
        if (device == null) {
            throw new BaseException("设备不存在");
        }
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            log.error("物联网接口 - 获取设备详情失败{}", response);
            throw new BaseException("物联网接口 - 获取设备详情失败");
        }
        deviceDetailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceDetailVo.setActiveTime(activeTime);
        }
        return deviceDetailVo;
    }

    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            log.error("物联网接口 - 获取设备影子失败{}", response);
            throw new BaseException("物联网接口 - 获取设备影子失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        //获取数组中第一个元素
        if (CollectionUtil.isEmpty(shadow)) {
            return Collections.emptyList();
        }
        DeviceShadowData deviceShadowData = shadow.get(0);

        JSONObject jsonObject = JSONUtil.parseObj(deviceShadowData.getReported().getProperties());
        List<DeviceDataVo> list = new ArrayList<>();
        String eventTimeStr = deviceShadowData.getReported().getEventTime();
        // 使用正确的日期格式解析
        LocalDateTime eventTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        // 日期时区转换
        eventTime = eventTime.atZone(ZoneId.of("UTC"))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        //笔记中的方法，基于AjaxResult返回类型实现
//        List<Map<String,Object>> list = new ArrayList<>();
        LocalDateTime finalEventTime = eventTime;
        jsonObject.forEach((k, v)->{
            DeviceDataVo deviceDataVo = new DeviceDataVo(k,finalEventTime,v);
            list.add(deviceDataVo);
        });
        return list;
    }

    /**
     * 删除设备
     *
     * @param iotId
     */
    @Override
    public void deleteDeviceByIotId(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        try {
            DeleteDeviceResponse response = client.deleteDevice(request);
        } catch (Exception e) {
            log.error("物联网接口 - 删除设备失败{}", e);
            throw new BaseException("物联网接口 - 删除设备失败");
        }
        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
        queryWrapper = queryWrapper.eq("iot_id", iotId);
        remove(queryWrapper);
    }
    /**
     * 查询产品详情
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        //参数校验
        if(StringUtils.isEmpty(productKey)){
            throw new BaseException("请输入正确的参数");
        }
        //调用华为云物联网接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = client.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }
        //判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)){
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }
}
